package Demo;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;



public class UdpEchoServer {
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动!");
        while (true) {
            DatagramPacket reqPacket = new DatagramPacket(new byte[1024], 1024);
            socket.receive(reqPacket);
            String request = new String(reqPacket.getData(), 0, reqPacket.getLength());
            String response = process(request);
            DatagramPacket resPacket = new DatagramPacket(response.getBytes(), response.getBytes().length
                    , reqPacket.getSocketAddress());
            socket.send(resPacket);
            System.out.printf("[%s:%d] req: %s, resp: %s\n", resPacket.getAddress(), resPacket.getPort()
                   , request, response);
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(8080);
        server.start();

    }
}
